﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Xml;
using System.IO;
using System.Xml.XPath;
using System.Threading;
using DBconnection;
using simulation;

namespace SocketConnections
{
    public static class PrSocket
    {
        private static IPAddress ipAdress = IPAddress.Parse("127.0.0.1");
        private static TcpListener myList = new TcpListener(ipAdress, 8000);
            
        public static void Sync()
        { 
            Console.WriteLine("Server running - Port: 8000");
            Console.WriteLine("Local end point:" +
                            myList.LocalEndpoint);
            Console.WriteLine("Waiting for connections...");
            myList.Start();
            try
            {
                Socket s = myList.AcceptSocket();

                // When accepted
                Console.WriteLine("Connection accepted from "
                             + s.RemoteEndPoint);
                Console.WriteLine("Waiting for dicitonary input");

                byte[] b = new byte[10000];
                int k = s.Receive(b);
                string XMLstr = System.Text.Encoding.UTF8.GetString(b).Trim(new char[] { '\0' });

                XmlDocument xml = new XmlDocument();
                xml.LoadXml(XMLstr);

                //OpenConenction
                DB.OpenConnection();

                foreach (XmlNode Class in xml.SelectNodes("//Class"))
                {
                    if (DB.SearchInDb(Class.Attributes["name"].Value))
                    {
                        DB.deleteAllParm(Class.Attributes["name"].Value); //Delete all parameters from tb[name]
                        string className = Class.Attributes["name"].Value;

                        foreach (XmlNode Parameter in Class.SelectNodes(".//Parameter"))
                        {
                            DB.insertParameter(className, Parameter.Attributes["Eng_Name"].Value, Parameter.Attributes["Heb_Name"].Value, Parameter.Attributes["Desc"].Value, Parameter.Attributes["Type"].Value);
                        }
                    }
                        
                    else if(!DB.SearchInDb(Class.Attributes["name"].Value))
                    {  
                        string className = Class.Attributes["name"].Value;
                        DB.insertClass(Class.Attributes["name"].Value, Class.Attributes["Heb_Name"].Value, Class.Attributes["Desc"].Value, Class.Attributes["Type"].Value);
                        foreach (XmlNode Parameter in Class.SelectNodes(".//Parameter"))
                        {
                            DB.insertParameter(className, Parameter.Attributes["Eng_Name"].Value, Parameter.Attributes["Heb_Name"].Value, Parameter.Attributes["Desc"].Value, Parameter.Attributes["Type"].Value);
                        }
                    }       
                }

                //Check if class in db not exist in xml
                string [] ex=DB.GetAllClassesInDB();
                int exist=0;
                for (int j = 0; j < ex.Length; j++)
                {
                    foreach (XmlNode Class in xml.SelectNodes("//Class"))
                    {
                        if (Class.Attributes["name"].Value.Equals(ex[j]))
                        {
                            exist = 1;
                        }
                    }

                    if (exist == 0)
                    {
                        //Not exist in Xml
                        DB.DeleteClass(ex[j]);
                        
                    }

                    exist = 0;
                }


                //Close Connection
                DB.CloseConnection();
            }
            catch
            {

            }
            Thread.CurrentThread.Abort();
        }

        public static void Input()
        {
            myList.Start();

           Socket s = myList.AcceptSocket();

           // When accepted
           //Console.WriteLine("Connection accepted from "
           //                  + s.RemoteEndPoint);

           while (true)
           {
               byte[] b = new byte[10000];
               int k = s.Receive(b);
               string XMLstr = System.Text.Encoding.UTF8.GetString(b).Trim(new char[] { '\0' });
               if (XMLstr != "")
               {
                   XmlDocument xml = new XmlDocument();
                   xml.LoadXml(XMLstr);

                   string command = "";

                   XmlNode Command = xml.SelectSingleNode("//Command");
                   command = Command.Attributes["type"].Value;

                   switch (command)
                   {
                       case "Delete":
                           Console.WriteLine("Delete Command Recived");
                           XmlNode Class = xml.SelectSingleNode("//Class");
                           Guid Guid = new Guid(Class.Attributes["Guid"].Value);
                           string Name = Class.Attributes["Name"].Value;
                           SIM.S_Delete(Name, Guid);

                           break;

                       //**********************************************************//

                       case "Add":
                           Console.WriteLine("Add Command Recived");
                           foreach (XmlNode Cls in xml.SelectNodes("//Class"))
                           {
                               Guid Ad_Guid = new Guid(Cls.Attributes["Guid"].Value);
                               string Ad_Name = Cls.Attributes["Name"].Value;

                               string[] Prms = new string[xml.SelectNodes("//Prm").Count];
                               int index = 0;

                               foreach (XmlNode Prm in xml.SelectNodes("//Prm"))
                               {
                                   Prms[index] = Prm.Attributes["Val"].Value;
                                   index++;
                               }
                               SIM.S_Add(Ad_Name, Ad_Guid, Prms);
                               
                           }

                           break;

                       //**********************************************************//

                       case "Mod":
                           Console.WriteLine("Update Command Recived");
                           foreach (XmlNode ModClass in xml.SelectNodes("//Class"))
                           {
                               string M_Name = ModClass.Attributes["Name"].Value;
                               Guid M_Guid = new Guid(ModClass.Attributes["Guid"].Value);
                               string M_PrmName = ModClass.Attributes["prm"].Value;
                               string M_Val = ModClass.Attributes["value"].Value;

                               SIM.S_Mod(M_Name, M_Guid, M_PrmName, M_Val);
                           }
                           break;
                   }
               }
               Array.Clear(b, 0, b.Length);
           }
        }

    }
}
